package com.example.myapplication.my_view_model

import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import com.example.myapplication.MyApplication

class ViewModePlus : AndroidViewModel {

    private val key = "key"
    private lateinit var handle: SavedStateHandle

    constructor(application: Application, savedStateHandle: SavedStateHandle):super(application){
        handle = savedStateHandle
        if (!handle.contains("key")){
            load()
        }
    }

    fun getLifeData():LiveData<Int>{
        return handle.getLiveData<Int>(key)
    }

    private fun load(){
        val application = getApplication<MyApplication>()
        val sharedP = application.getSharedPreferences("Name",Context.MODE_PRIVATE)
        val value = sharedP.getInt(key,0)
        handle[key] = value
    }

    fun add(v: Int){

        var value = getLifeData().value
        if (value != null){
            handle[key] = value!! + 1
        }
        save()
    }

    private fun save(){
        val application = getApplication<MyApplication>()
        val sharedP = application.getSharedPreferences("Name",Context.MODE_PRIVATE)
        val edit = sharedP.edit()
        var value = getLifeData().value
        if (value != null){
            edit.putInt(key,value!!)
        }
    }
}